import { Helper } from  "../helper"
import { ShowTotpInfo, ListPage} from "./totp-page"
import {TotpStorage}  from "../../biz/storage/totp-storage"

class TermDialog {
  visible: boolean;//visible of term dialgo
  checkboxTipsVisible: boolean;//internal status
  isCountdownFinished: boolean;//internal status

  buttons: any[];
  terms: any[];

  constructor() {
    this.visible = true; //visible of term dialgo

    this.checkboxTipsVisible = true; //internal status
    this.isCountdownFinished = false; //internal status

    this.buttons = [
      { text: '同意', type: 'primary', countdownTime: 10, },
      { text: '拒绝', aide: true, type: 'default', } ,
    ];
    this.terms = [
      { name: '《用户协议》', key: 'user' }
    ];
  }
}

Page<{
  helper: Helper;
  totpInfo: ShowTotpInfo[];
  timer: number;
  page: ListPage;

  popupVisible: boolean;
  key: string;

  showModifyDialog: boolean;
  description: string;

  //term dialog 
  termDialogVisible: boolean;//visible of term dialgo
  checkboxTipsVisible: boolean;//internal status
  isCountdownFinished: boolean;//internal status

  termDialogButtons: any[];
  terms: any[];
}, {
  cb_timer(): void;
  catchTapEachItem(e):void;

  catchTapDeleteTotpItem(e): void;
  handlePopupClose(): void;


  catchTapModifyTotpItem(e): void;
  closeModifyDialog(): void;
  onChangeDescription(value: string, e: Event): void;
  onButtonConfirmModifyDialog(): void;
  onButtonCancelModifyDialog(): void;


  //term related:
  showTabBar(show:boolean):void;
  showTermDialog(isShow: boolean): void;

  showTipsWithChecked(checked: boolean): void;
  handleCheckChange(checked: boolean): void;
  handleTermPrefixTap(checked: boolean): void;

  handleCountdownFinished(item?:any, index?:number, event?: Event): void;

  handleButtonTap(item?: any, index?:number, checked?:boolean, event?: Event): void;
  handleTermTap(item?: any, index?: number, event?: Event): void;
}>({
  data: {
    helper: new Helper(),
    totpInfo: [],
    timer: undefined,
    page: undefined,

    popupVisible: false,
    key: '',

    showModifyDialog: false,
    description: '',

    termDialogVisible : false, //visible of term dialgo

    checkboxTipsVisible : true, //internal status
    isCountdownFinished : false, //internal status
    termDialogButtons : [
      { text: '同意', type: 'primary', countdownTime: 10},
      { text: '拒绝', aide: true, type: 'default' } ,
    ],
    terms : [
      { name: '《用户协议》', key: 'user' }
    ],
  },


  showTabBar(show: boolean): void {
    if(show){
      my.showTabBar({
        animation: false,
        success: function(res) {
          //console.log('show tab bar success', res); // { "success": true}
        },
        fail: function(err) {
          console.log('show tab bar failed', err);
        }
      });
    }
    else{
      my.hideTabBar({
        animation: false,
        success: function(res) {
          //console.log('hide tab bar success', res); // { "success": true}
        },
        fail: function(err) {
          console.log('hide tab bar failed', err);
        }
      });
    }
  },
  showTermDialog(isShow: boolean = true): void {
    this.setData({
      termDialogVisible: isShow,
    });
  },
  showTipsWithChecked(checked: boolean): void {
    if(checked == false){
      this.setData({
        checkboxTipsVisible: true
      });
    }
    else{
      this.setData({
        checkboxTipsVisible: false,
      });
    }
  },
  handleCountdownFinished(b, index, event): void {
    this.data.isCountdownFinished = true;
  },
  handleCheckChange(checked: boolean){
    //console.log("handle checked change");
    this.showTipsWithChecked(checked);
  },
  handleTermPrefixTap(checked: boolean) {
    this.showTipsWithChecked(checked);
  },
  handleButtonTap(item, index, checked, event) {
    if(index == 0){ // confirm button
       if(this.data.isCountdownFinished
         && checked){
        this.setData({
           termDialogVisible : false,
         });

        this.data.helper.getIsTermAgree().set(true);
        this.data.helper.getIsTermAgree().save();
      
        this.showTabBar(true);
       }
       else{
         if(checked == false){
           my.showToast({ content: `请同意用户隐私政策` });
         }
         else{
           if(this.data.isCountdownFinished == false){
             my.showToast({ content: `请仔细阅读用户隐私政策` });
           }
         }
       }
     }
     else if (index == 1) { // rejuse button
       my.showToast({ content: `请仔细阅读用户隐私政策`});
     }
     else{
       console.error(`click button index:${index} error`);
     }
  },
  handleTermTap(item, index, event) {
    //my.showToast({ content: `点击了第 ${index + 1} 个协议` });
  },




  onLoad(query) {
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
    
    const isTermAgree = this.data.helper.getIsTermAgree().get();
    //console.log("Term Agree: ", isTermAgree)
    if( isTermAgree == undefined || isTermAgree == false){ 
      //TODO: clear all storage
      this.data.helper.getIsTermAgree().storage.clear();

      this.showTabBar(false);

      //show Term Agree Dialog 
      this.showTermDialog(true);
    } 

    let totpInfos = this.data.helper.getTotpInfo();
    this.data.page = new ListPage(totpInfos);
    
    if(this.data.timer === undefined){
      this.data.timer = setInterval((): void => {
        this.cb_timer();
      }, 1000, this)
    }
    else{
      console.log("timer: ", this.data.timer)
    }
  },
  onReady() {
    // 页面加载完成
  },
  cb_timer(): void {
    this.data.page.updateTimestamp();
    this.setData({
      totpInfo: this.data.page.toShowInfo()
    })
  },
  onShow() {
    let totpInfos = this.data.helper.getTotpInfo();
    this.data.page = new ListPage(totpInfos);

    // 页面显示
    this.setData({
      totpInfo: this.data.page.toShowInfo()
    })
  },
  onUnload() {
    // 页面被关闭
    if(this.data.timer !== undefined){
      clearInterval(this.data.timer)
      this.data.timer = undefined;
    }
    this.data.page = undefined;
    //console.log("Page Unloaded")
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },
  catchTapEachItem(e) {
    const key = e.target.dataset.key;
    const description = e.target.dataset.description;
    //console.log(key, description);

    this.setData({
      popupVisible: true,
      key: key,
      description: description,
    })
  },
  catchTapDeleteTotpItem(e) {
    const key = e.target.dataset.key;
    this.data.helper.getTotpInfo().delete(key);
    this.setData({
      popupVisible: false,
      key: '',
    })
    const r = TotpStorage.fromDefault().save(this.data.helper.getTotpInfo());
    if(r == true ) {
      console.debug("delete descript => save to cache ok!", r);
    }
    else{
      console.debug("delete descript => save to cache failed!", r);
    }
  },
  handlePopupClose() {
    this.setData({
      popupVisible: false,
      key: '',
    })
  },


  catchTapModifyTotpItem(e) {
    const key = e.target.dataset.key;
    const description = e.target.dataset.description;
    //console.log(`modify the key:${key}, desc: ${description}`)

    this.setData({
      showModifyDialog: true,
      description: description,
    });
  },
  onChangeDescription(value: string, e: Event) {
    this.setData({
      description: value,
    });
  },
  onButtonConfirmModifyDialog(): void {
    //get key & description for this item
    const key = this.data.key;
    const description = this.data.description;
    //console.log(`onButtonConfirmModifyDialog -> key:${key}, desc:${description}`);
    //save description into this item
    let item = this.data.helper.getTotpInfo().get(key);
    if(item !== undefined) {
      item.data.description = description;
    }

    const r = TotpStorage.fromDefault().save(this.data.helper.getTotpInfo());
    if(r == true ) {
      console.debug("modify descript => save to cache ok!", r);
    }
    else{
      console.debug("modify descript => save to cache failed!", r);
    }

    this.closeModifyDialog();
    this.handlePopupClose();
  },
  onButtonCancelModifyDialog(): void {
    this.closeModifyDialog();
    this.handlePopupClose();
  },
  closeModifyDialog() {
    this.setData({
      showModifyDialog: false,
      description: '',
    });
  }
});
